package com.acmen.easyapi.web;


import com.acmen.easyapi.service.AppService;
import com.acmen.easyapi.model.Response;
import com.acmen.easyapi.model.App;
import com.acmen.easyapi.model.MenuTree;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author acmen
 * 接口文档服务
 * @date 2022-03-16
 */
@Controller
public class AppController {
    @Autowired
    private AppService appService;

    /**
     * 接收同步过来的接口文档
     * @param request
     * @param response
     * @param app
     * @throws IOException
     */
    @PostMapping(value = "/app/sync")
    public void sync(HttpServletRequest request, HttpServletResponse response, @RequestBody App app) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        try{
            appService.sync(request,app);
            response.getWriter().println(JSON.toJSONString(Response.success()));
        }catch (Exception e){
            e.printStackTrace();
            response.getWriter().println(JSON.toJSONString(Response.failure("同步失败"+e.getMessage())));
        }
    }

    @RequestMapping(value = "/app/{appName}", method = RequestMethod.GET)
    public String appDetail(HttpServletRequest request, ModelMap model,@PathVariable("appName") String appName) {
        return appService.appDetail(request,appName,model);
    }

    @RequestMapping(value = {"/app/note"}, method = RequestMethod.GET)
    public String note(HttpServletRequest request, ModelMap model) {
        return appService.note(request,model);
    }

    @RequestMapping(value = {"/app/auth"}, method = RequestMethod.GET)
    public String auth(HttpServletRequest request, ModelMap model) {
        model.put("contextPath", request.getContextPath());
        return "/app/auth";
    }

    @RequestMapping(value = {"/app/api-tree"}, method = RequestMethod.GET)
    public String export(HttpServletRequest request, ModelMap model) {
        model.put("contextPath", request.getContextPath());
        String appName = request.getParameter("appName");
        model.put("appName", appName);
        MenuTree menuTree = appService.getApiMenuTree(appName);
        model.put("menuTree", JSON.toJSONString(menuTree));
        return "/app/api-tree";
    }

    @PostMapping(value = "/app/export")
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
        appService.export(request,response);
    }
}
